package com.cqhz.quwan.ui.base

import android.support.v4.app.Fragment
import android.widget.RadioGroup
import com.cqhz.quwan.util.v

abstract class AbsTabActivity : AbsActivity() {
    private val tabRadioGroup: RadioGroup by v(initTabRadioGroup())
    private val fragments: List<Fragment> by initFragments()
    private val tabs: IntArray by initTabResIds()
    private var currentFragment: Fragment? = null
    private val addedFragment = ArrayList<String>()
    private var isFirstIn: Boolean = true
    override fun initView() {
        if (isFirstIn) {
            isFirstIn = false
            showFragment(fragments[2])
        }
        tabRadioGroup.setOnCheckedChangeListener { _, checkedId ->
            showFragment(fragments[tabs.indexOf(checkedId)])
        }
        initData()
    }

    abstract fun initData()
    private fun showFragment(frag: Fragment) {
        if (frag == currentFragment) {
            return
        }
        val transaction = supportFragmentManager.beginTransaction()
        if (currentFragment != null) {
            transaction.hide(currentFragment)
        }
        if (frag.isAdded) {
            transaction.show(frag)
        } else if (!addedFragment.contains(frag.javaClass.simpleName)) {
            transaction.add(contentViewResId(), frag)
            addedFragment.add(frag.javaClass.simpleName)
        }
        transaction.commitAllowingStateLoss()
        currentFragment = frag
    }

    private fun initTabRadioGroup(): Int {
        return tabRadioGroupResId()
    }

    private fun initFragments(): Lazy<List<Fragment>> {
        return lazy { fragments() }
    }

    private fun initTabResIds(): Lazy<IntArray> {
        return lazy { tabResIds() }
    }

    fun checkIndex(index: Int) {
        tabRadioGroup.check(tabs[index])
    }

    abstract fun contentViewResId(): Int
    abstract fun tabRadioGroupResId(): Int
    abstract fun tabResIds(): IntArray
    abstract fun fragments(): List<Fragment>
}